<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addRole"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table
              :data="list"
              style="width: 100%"
              :border="true"
            >
              <el-table-column align="center" label="序号" width="120">
                <template #default="{$index}">
                  <!-- 真正的序号应该是
                  之前页面(前一页)的所有数据长度开始 +1 +2 +3 ... -->
                  {{ (params.page - 1) * params.pagesize + $index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                prop="name"
                label="角色名称"
                width="120"
              />
              <el-table-column
                align="center"
                prop="description"
                label="描述"
              />
              <el-table-column
                align="center"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button size="small" type="success" @click="prermRole(scope.row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(scope.row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                layout="prev,pager,next"
                :total="params.total"
                :page-size="params.pagesize"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <addDeptVue
      :show-dialog.sync="showDialog"
      :title="title"
      :role-detail="roleDetail"
      @sumbit="addRole"
    />
    <el-dialog
      title="分配权限"
      :visible="showPermDialog"
      @close="btnCancel"
    >
      <!-- 权限是一颗树 -->
      <!-- 将数据绑定到组件上 -->
      <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
      <!-- id作为唯一标识 -->
      <el-tree
        ref="permTree"
        :data="permList"
        :props="defaultProps"
        :check-strictly="true"
        default-expand-all
        show-checkbox
        node-key="id"
      />
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, deleteRole, getRoleDetail, addRole, updateRole, assignPerm } from '@/api/setting'
import { mapGetters } from 'vuex'
import addDeptVue from './components/add-dept.vue'
import { getPermissionList } from '@/api/permisson'
export default {
  components: {
    addDeptVue
  },
  data() {
    return {
      list: [],
      permList: [], // 权限树形数据
      roleId: '', // 分配权限ID
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      params: {
        page: 1, // 当前页
        pagesize: 2, // 一页几条
        total: 0 // 总数
      },
      formData: {
        name: '',
        remarks: '',
        mailbox: '',
        companyAddress: ''
      },
      roleDetail: {},
      showDialog: false,
      title: '',
      showPermDialog: false
    }
  },
  computed: {
    ...mapGetters(['companyId'])
  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
    this.getPermissionList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleList(this.params.page, this.params.pagesize)
      // console.log(res)
      const { total, rows } = res
      this.params.total = total
      this.list = rows
      // this.params.pagesize = this.list.splice(0, 6)
    },
    // 获取公司信息
    async getCompanyInfo() {
      const res = await getCompanyInfo(this.companyId)
      this.formData = res
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      // 显示enVisible为1的权限名称
      this.permList = this.listData(res.filter(item => item.enVisible === '1'), '0')
      // console.log(this.permList)
    },
    // 树形数据
    listData(list, tolPid) {
      const arr = []
      list.forEach(item => {
        if (item.pid === tolPid) {
          item.children = this.listData(list, item.id)
          arr.push(item)
        }
      })
      return arr
    },
    // 分配权限
    async prermRole(id) {
      this.roleId = id
      this.showPermDialog = true
      const { permIds } = await getRoleDetail(id)
      // console.log(permIds)
      // 用setCheckedKeys匹配node-key的id显示哪个复选框被选中
      this.$nextTick(() => {
        this.$refs.permTree.setCheckedKeys(permIds)
      })
    },
    handleCurrentChange(val) {
      // val是当前点击的页码
      this.params.page = val // 将当前页码赋值给当前的最新页码
      this.getRoleList()
    },
    // 提交 确定按钮
    async addRole(data, bl) {
      this.title = '新增角色'
      this.showDialog = true
      if (bl) {
        // 只有校验通过的情况下 才会执行await的下方内容
        console.log(data)
        // 要分清楚现在是编辑还是新增
        if (data.id) {
          // 编辑模式  调用编辑接口
          await updateRole(data)
          this.$message.success('编辑成功')
        } else {
          // 新增业务
          await addRole(data)
          this.$message.success('新增成功')
        }
        // 关闭dialog
        this.showDialog = false
        // 刷新列表
        this.getRoleList()
      }
    },
    // 编辑角色
    async editRole(id) {
      this.title = '编辑角色'
      this.showDialog = true
      this.roleDetail = await getRoleDetail(id)
    },
    // 删除角色
    async deleteRole(id) {
      try {
        await this.$confirm('确认删除该角色吗？')
        // 只有点击了确定 才能进入到下方
        await deleteRole(id) // 调用删除接口
        // 当前页数量长度等于1且页码要大于1时候 就让页码减1
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page -= 1
        }
        this.getRoleList() // 重新加载数据
        this.$message.success('删除角色成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 权限取消
    btnCancel() {
      // 关闭弹窗的时候清空勾选的节点，使得下次打开弹窗没有上一次的残留
      this.$refs.permTree.setCheckedKeys([])
      this.showPermDialog = false
    },
    // 权限确定
    async btnOK() {
      // 给角色分配权限
      // getCheckedKeys()获取被选中的复选框
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      // 提示
      this.$message.success('权限分配成功')
      this.showPermDialog = false
    }
  }
}
</script>

<style>

</style>
